<template>
  <div>
    <Drawer
      ref="modal"
      :title="`${editType === 'create' ? $t('visitorsIndex.visitorsAddU') : $t('visitorsIndex.visitorsEdit')}`"
      :width="600"
      :value="show"
      :beforeClose="$_modal_decideIfClose"
    >
      <Form
        ref="form"
        :labelWidth="150"
        :model="formData"
        :rules="formRule"
      >
        <FormItem :label="$t('visitorsIndex.visitorsDestination')">
          <div>{{$t('visitorsIndex.visitorsFace')}}</div>
        </FormItem>
        <FormItem prop="deviceType" :label="$t('newDevices.siteName')">
          <!-- <Select
            style="width:200px"
            v-model="formData.deviceType"
            :placeholder="$t('visitorsIndex.visitorsSelArea')"
          >
            <Option
              v-for="(item, idx) in deviceType" :key="idx"
              :value="item.id"
              :label="item.areaName"
            >
            </Option>
          </Select> -->
		  	<Cascader style="width: 200px;display:inline-block" :data="recordTypes" v-model="recordType" :clearable="false"
              @on-change="handleChange1" :placeholder="$t('newDevices.selectSite')"
               change-on-select>
        	</Cascader>
        </FormItem>
		<FormItem  :label="$t('visitorsIndex.visitorsNameTable')" :required="true">
          <input  class="cssAll" :placeholder="$t('visitorsIndex.visitorsInputName')"  type="text" value="" id="personName"/>

        </FormItem>
        <FormItem prop="phone" :label="$t('visitorsIndex.visitorsPhone')">
          <Input maxlength="11" type="tel" v-model="formData.phone" :placeholder="$t('visitorsIndex.visitorsPhoneInput')" />
        </FormItem>
        <FormItem prop="IDcareType" :label="$t('visitorsIndex.visitorsIDType')">
          <Select
            style="width:200px"
            @on-change = "onSelectIDcard"
            v-model="formData.IDcareType"
            :placeholder="$t('visitorsIndex.visitorsIDTypeSel')"
          >
            <Option
              v-for="(item, idx) in IDcareType" :key="idx"
              :value="item.value"
              :label="item.name"
            >
            </Option>
          </Select>
        </FormItem>
        <FormItem  :label="$t('staffIndex.staffeCertNumber')" :required="true">
          <input class="cssAll" :placeholder="$t('companyManagement.pleaseEnter')+$t('staffIndex.staffeCertNumber')"  type="text" value="" id="IDcareNum"/>
          <Button v-show="ifAdvanced" type="primary" @click="aaaa()" style="margin-left: 20px;">{{$t('visitorsIndex.visitorsReadCard')}}</Button>
        </FormItem>
        <FormItem prop="startday" :label="$t('visitorsIndex.visitorsStartTime')">
          <DatePicker
		 	style="width:280px"
	
            v-model="formData.startday"
            :value="formData.startday"
            @on-change="startdayChange"
            format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            :placeholder="$t('visitorsIndex.visitorsStartTimeSel')"
          />
        </FormItem>
        <FormItem prop="endDay" :label="$t('visitorsIndex.visitorsEndTime')">
          <DatePicker
		 	style="width:280px"
            v-model="formData.endDay"
            :value="formData.endDay"
            @on-change="endDayChange"
            format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            :placeholder="$t('visitorsIndex.visitorsEndTimeSel')"
          />
        </FormItem>
        <FormItem  v-show="!ifAdvanced"  :label="$t('visitorsIndex.visitorsHead')">
          <div
            v-if="editType === 'update' && !ifSelFile && formData.photo"
            class="img"
          >
            <img style="width: 120px" :src="getPhoto(formData.photo)" >
          </div>
          <Upload
            v-model="formData.file"
            action="/"
            :before-upload="handleUpload"
            :format="['jpg','png']"
            :max-size="204800"
          >
            <Button icon="ios-cloud-upload-outline">{{ $t("staffIndex.staffDepartPhotoSel") }}</Button>
          </Upload>
          <span v-if="ifSelFile">{{ formData.file.name }}</span>
        </FormItem>

        <FormItem v-show="ifAdvanced"  :label="$t('visitorsIndex.visitorsHead')">
          <div class="img" >
            <img width="120px" height="140px" src="../../../assets/userImage.png"  style="margin-left:5px" id="id_img_pers"/>
          </div>
        </FormItem>
        <FormItem class="glo-btn-group">
          <Button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >{{ $t("devicesCreate.devCreateSubmit") }}</Button>
          <Button
            @click="$_modal_close"
          >{{ $t("devicesCreate.devCreateCancel") }}</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>

<script>
// import Vue from 'vue'
import _ from 'lodash'
import $ from 'jquery'
import {
  format
} from '@/utils/auth.js'

import {
  mapState,
} from 'vuex'
import {
  getPhoto,
} from '@/api/public.js'
import modalMixin from '@/utils/mixins/modalMixin.js'
import {
  create,
  update,
  getListArea,
} from '@/api/visitors.js'
import {
  getSite,
  getParentArea,
} from '@/api/newDevices.js'
// console.log(Vue)

const DEFAULT_FORM = {
  file: '',
  deviceType: '',
  name: '',
  phone: '',
  startday: '',
  endDay: '',
  IDcareType: '',
  IDcareNum: '',
}
var ZK = 
			{
				extend : function()
				{
					// inline overrides  
					var io = function(o)
					{
						for ( var m in o)
						{
							this[m] = o[m];
						}
					};
					var oc = Object.prototype.constructor;

					return function(sb, sp, overrides)
					{
						if (typeof sp == 'object')
						{
							overrides = sp;
							sp = sb;
							sb = overrides.constructor != oc ? overrides.constructor : function()
							{
								sp.apply(this, arguments);
							};
						}
						var F = function()
						{
						}, sbp, spp = sp.prototype;
						F.prototype = spp;
						sbp = sb.prototype = new F();
						sbp.constructor = sb;
						sb.superclass = spp;
						if (spp.constructor == oc)
						{
							spp.constructor = sp;
						}
						sb.override = function(o)
						{
							ZK.override(sb, o);
						};
						sbp.override = io;
						ZK.override(sb, overrides);
						sb.extend = function(o)
						{
							ZK.extend(sb, o);
						};
						return sb;
					};
				}(),

				override : function(origclass, overrides)
				{
					if (overrides)
					{
						var p = origclass.prototype;
						for ( var method in overrides)
						{
							p[method] = overrides[method];
						}
					}
				},

				apply : function(o, c, defaults)
				{
					if (defaults)
					{
						// no "this" reference for friendly out of scope calls  
						ZK.apply(o, defaults);
					}
					if (o && c && typeof c == 'object')
					{
						for ( var p in c)
						{
							o[p] = c[p];
						}
					}
					return o;
				}
			};







var Device = function()
{
	message : ""
};
function createISSonlineDevice(setting)
{ 
	var ISSOnline = "ZKIDROnline";
	var browserFlag = getBrowserType() || "";
	//刷卡信息返回默认方法
	if(typeof setting.Methods == "object")
	{
		if(typeof setting.Methods.showMessage != "function")
		{
			setting.Methods.showMessage = function(type,message)
			{
				$("#cert_message").text(message);
				$("#cert_message_type").text(msgType[type]);
			}
		}
		//检查驱动安装默认方法
		if(typeof setting.Methods.checkWebServer != "function")
		{ 
			setting.Methods.checkWebServer = function(myDevice)
			{ 
				var ISSVersion = function(){};
				ZK.extend(ISSVersion, Device, {
					message : "",
					url : "/info",
					interfaceResult : 
					{
						0:{mean:"成功",message:"二代身份证读取成功！",type:"success",notShow:true}
					},
					dealDeviceData:function(result){
						console.log(result)
						var existVersion = result.data.server_version;//2.7.1
						var curVersion = "${application['fpDriver.version']}";//3.5.2
						var existVersionArr = existVersion.split(".");
						var curVersionArr = curVersion.split(".");
						var isLast = true;
						var len = existVersionArr.length;
						for(var i=len;i>0;i--)
						{
							var existVersionTemp = parseInt(existVersionArr[i-1]);
							var curVersionTemp = parseInt(curVersionArr[i-1]);
							if(existVersionTemp<curVersionTemp)
							{
								isLast = false;
							}
							else if(existVersionTemp>curVersionTemp)
							{
								isLast = true;
							}
							else
							{
								//等于 忽略
							}
						}
						 
						if(isLast)
						{
							if(typeof setting.Methods.detectSuccess == "function")
							{
								setting.Methods.detectSuccess();
							}
							if(typeof myDevice == "object")
							{
								//连接设备，处理返回信息
								setTimeout(function(){
									myDevice.accessDevice();
								},100);
							}
						}
						else
						{
							if(typeof setting.Methods.detectWarning == "function")
							{
								setting.Methods.detectWarning();
							}
							if(typeof myDevice == "object")
							{
								//连接设备，处理返回信息
								setTimeout(function(){
									myDevice.accessDevice();
								},100);
							}
							else
							{
								if(typeof setting.Methods.notInstall == "function")
								{
									setting.Methods.notInstall();
								}
							}
						}
					},
					installDrive:function(){
						if(typeof setting.Methods.detectError == "function")
						{
							setting.Methods.detectError();
						}
						if(typeof myDevice == "object")
						{
							closeMessage();
							//驱动未安装
							setting.Methods.downloadDrive();
						}
						else
						{
							if(typeof setting.Methods.notInstall == "function")
							{
								setting.Methods.notInstall();
							}
						}
						
						return false;
					}
				});
				 
				var version = new ISSVersion();
				version.accessDevice();
			}
		}
		//下载驱动默认方法
		if(typeof setting.Methods.downloadDrive != "function")
		{
			setting.Methods.downloadDrive = function()
			{
				alert('请安装驱动程序')
			}
		}
	}
	/**
	 * 设备
	 */
	
	var buttonNames = {"Cert":"","Scanner":"","Barcode":""};
	if(typeof setting.Cert == "object")
	{
		buttonNames.Cert = setting.Cert.select;
		//身份证阅读器
		var Cert = function(){};
		ZK.extend(Cert, Device, {
			//提示信息
			message : "请将二代身份证放到读卡区域...",
			//服务url
			url : "/ScanReadIdCardInfo?OP-DEV=1&CMD-URL=4&REPEAT=1&common=1" + "&random=" + getRandomNum(),
			//接口返回值
			interfaceResult : 
			{
				0:{mean:"成功",message:"二代身份证读取成功！",type:"success"},
				1:{mean:"端口打开失败",message:"未检测到二代身份证阅读器！",type:"warning"},
				2:{mean:"数据传输超时",message:"未检测到二代身份证阅读器！",type:"error"},
				10:{mean:"没有找到卡",message:"未读取到身份证，请重新刷卡！",type:"warning"},
				11:{mean:"读卡操作失败",message:"未检测到二代身份证阅读器！",type:"error"},
				20:{mean:"自检失败",message:"二代身份证读取失败！",type:"error"},
				30:{mean:"其他错误",message:"二代身份证读取失败！",type:"error"},
				40:{mean:"相片解码失败",message:"二代身份证读取失败！",type:"error"},
				100:{mean:"超时",message:"未读取到身份证，请重新刷卡！",type:"warning"},
				200:{mean:"GetBase64PhotoData",message:"二代身份证读取失败！",type:"error"}
			},
			dealDeviceData:setting.Cert.callBack
		});
	}
	
	//工厂
	var DeviceFactory = 
	{
		createDevice : function(button){
			var device;
			switch(button){
				case "Cert":
					device = new Cert();
					break;
				case "Scanner":
					device = new Scanner();
					break;
				case "Barcode":
				default:
					device = new BarcodeScanner();
					break;
			}
			return device;
		}
	}
	//设备工厂
	Device.prototype.createDevice = function(button)
	{
		return DeviceFactory.createDevice(button);
	};
	//信息显示
	Device.prototype.setMessage = function()
	{ 
		setting.Methods.showMessage(msgType.loading,this.message);
	};
	
	//处理硬件返回值
	Device.prototype.dealDeviceInfo = function(result)
	{
		if(result === null||result.ret===null)
		{
			setting.Methods.showMessage("error","设备连接异常");
			return;
		}
		//信息提示
		var info = this.interfaceResult[result.ret];
		if(info == undefined)
		{
			setting.Methods.showMessage("error","设备连接异常");
			return;
		}
		if(info.notShow == undefined)
		{
			setting.Methods.showMessage(info.type,info.message);
		}
		//处理数据
		if("success" === info.type)
		{
			this.dealDeviceData(result);
		}
	};
	
	//html5使用ajax方式访问服务
	Device.prototype.ajaxAccess = function(url)
	{ 
		console.log('我进来啦')
    console.log(url)
    // return
		var result = null;
		var parent = this;
		$.ajax({
			type : "GET",
			url : issOnlineUrl + url,
			dataType : "text",
			async:true,
			timeout:10000,
			success : function(data)
			{ 
        console.log(data)
				data = data.replace(/\\/g,"/");
				try{
					result = JSON.parse(data);
				}catch(e){
					// 修改啦让他不报错=============
					
					console.log('我是不是没有安装=====',data)
					if(!data) return
					result = eval("("+data+")");
		

				}
				parent.dealDeviceInfo(result);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) 
			{
        console.log(999999)
				 
				console.info(errorThrown+"url:"+url);
				if(textStatus == "timeout" && url != "/info")
				{
					setting.Methods.showMessage("warning","未读取到身份证，请重新刷卡！");
				}
				else if(typeof parent.installDrive == "function")
				{
					if(parent.installDrive())
					{
						setting.Methods.showMessage("error","设备连接异常");
					}
				}
				else
				{
					setting.Methods.showMessage("error","设备连接异常");
				}
			}			
		});
	};
	
	//IE8、IE9访问服务
	Device.prototype.xDomainAccess = function(url)
	{
		var parent = this;
		var xDomainRequest = new XDomainRequest();
		if (xDomainRequest) 
		{ 
			xDomainRequest.timeout=10000;
			xDomainRequest.open('GET', issOnlineUrl + url);
			xDomainRequest.onload = function()
			{
				var resultData = xDomainRequest.responseText;
				resultData = resultData.replace(/\\/g,"/");
				var obj = JSON.parse(resultData);
				parent.dealDeviceInfo(obj);
			};
			xDomainRequest.onerror = function()
			{
				//用完后，将对象置为空
				xDomainRequest = null;
				setting.Methods.showMessage("error","设备连接异常");
			};
			xDomainRequest.ontimeout = function()
			{
				//用完后，将对象置为空
				xDomainRequest = null;
				setting.Methods.showMessage("error","设备连接异常");
			};
			xDomainRequest.send();
		}
	};
	
	//驱动检测
	Device.prototype.installDrive = function()
	{
		return true;
	};
	//设备通信,得到硬件返回的数据
	Device.prototype.accessDevice = function()
	{
		$("#iss").css("width","25%");
		if(browserFlag == "html5"||browserFlag == "simple")
		{
			this.ajaxAccess(this.url);
		}
		else if(browserFlag == "simple")
		{
			this.xDomainAccess(this.url);
		}
		else
		{
			if(window.console)
			{
				console.error("browserFlag is missing");
			}
		}
	};
	
	Device.prototype.startFun = function()
	{
		console.log(123456888)
		//创建设备
		var device = new Device();
		var myDevice = device.createDevice("Cert");
		//显示提示信息
		myDevice.setMessage();
		setting.Methods.checkWebServer(myDevice);
	};

	setting.Methods.checkWebServer();
}

function DoGetSNR()
{
	$.ajax( {
		type : "GET",
		url : "http://127.0.0.1:24010/ZKIDROnline/MFCard?OP-DEV=1&CMD-URL=1&iPort=3",
		dataType : "json",
		async: true,
		success : function(data) 
		{
			//返回码
			var ret = null;
 			ret = data.ret;
 			//接口调用成功返回时
 			if(ret == 0)
			{
				alert("ICSnr:" + data.data.ICSnr);
			}
			else
			{
				alert("ret:" + data.ret);
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) 
		{
			alert("请安装IDROnline SDK!");
	    }
	});
}

var issOnlineUrl = "http://127.0.0.1:24010/ZKIDROnline";
var browserFlag = getBrowserType();
	var setting = {
			Cert : {
				callBack : function(result){
					setCertificateData(result);
				},
				select : "#button_readID"
			},
			Methods : {
				showMessage : function(type,message){
					$("#cert_message").text(message);
					$("#cert_message_type").text(msgType[type]);
				},
				downloadDrive : function(){
					alert('请安装驱动程序')
				}
			}
		}
		createISSonlineDevice(setting);
//});
//});

function setCertificateData(result)
{
  var imgData 
  console.log(result)
  var ValidDate = insertStr(insertStr(result.Certificate.ValidDate,'4','-'),'7','-')
 var Birthday = insertStr(insertStr(result.Certificate.Birthday,'4','-'),'7','-')
	// $("#birthday").val(Birthday.replace(/\./g,"-").substr(0,10));
	$("#IDcareNum").val(result.Certificate.IDNumber);
  // $("#idIssued").val(result.Certificate.IDIssued);

//   var a = result.Certificate.ValidDate.slice(0, 4) + '-' + result.Certificate.ValidDate.slice(4)
//   var b = a.slice(0, 7) + '-' + a.slice(7)
//  console.log(b)

 
  console.log(ValidDate)
  console.log(Birthday)
  // result.Certificate.IssuedData+"-"+
	// $("#IDcareNum").val(ValidDate);
	
	imgData =result.Certificate.Base64Photo;
	$("#id_img_pers").attr("src","data:image/jpg;base64,"+imgData);
	// $("#personIdPhoto").val(imgData);
	// $("#personPhoto").val("");
	
  $("#personName").val(result.Certificate.Name);
	// $("#gender").val(result.Certificate.Sex);
	// $("#nation").val(result.Certificate.Nation);
	// $("#address").val(result.Certificate.Address);
}
	
function getRandomNum() 
{
    var random = parseInt(Math.random() * 10000);
    return random;
}

//消息控件的使用类型的类
var msgType = 
{
	info : "info",
	success : "success",
	warning : "warning",
	error : "error",
	loading : "loading"
};

function getBrowserType()
{
	var browserFlag = "";
	 //是否支持html5的cors跨域
    if (typeof(Worker) !== "undefined")
    {
        browserFlag = "html5";
    }
    //此处判断ie8、ie9
    else if(navigator.userAgent.indexOf("MSIE 7.0")>0||navigator.userAgent.indexOf("MSIE 8.0")>0 || navigator.userAgent.indexOf("MSIE 9.0")>0)
    {
        browserFlag = "simple";
    }
    else
	{
		browserFlag = "upgradeBrowser";//当前浏览器不支持该功能,请升级浏览器
	}
    return browserFlag;
}


function openMessage(type, text, ptimeout)
{ 
	text = (text == "" ? null : text);
	var timeout = 1000;
	if(type == msgType.warning || type == msgType.info)//警告
	{
		timeout = 3000;
	}
	else if(type == msgType.success)//成功 
	{
		
		text = (text && text != null ? text : "操作成功");//${common_op_succeed}:操作成功
		var num = strlen(text)/30;
		num = num > 8 ? 8 : num;
		timeout = Math.ceil(num) * timeout;//动态判断显示字符数的长度来延长显示时间
	}
	else if(type == msgType.error)//失败
	{
		text = (text && text != null) ? text : "操作失败";//${common_op_failed}:操作失败，程序出现异常
		timeout = 3000;
	}
	else if(type == msgType.loading)//处理中
	{
		timeout = 0;//当为'loading'时，timeout值会被设置为0，表示不会自动关闭。
		text = text && text != null ? text : "处理中";//${common_op_processing}:处理中
	}
	var width = strlen(text) * 6.1 + 45;//按字符计算宽度
	timeout = ptimeout ? ptimeout : timeout;
	$.jBox.tip(text, type,{timeout: timeout, width: (width > 400 ? 400 : "auto")});//设定最大宽度为400
}


function closeMessage(timeout)
{
	timeout = timeout ? timeout : 1000;
	window.setTimeout("$.jBox.closeTip();", timeout);//设定最小等待时间
}

function strlen(str)
{  
    var len = 0;  
    if(str != null)
    {
   		for (var i=0; i<str.length; i++)
    	{   
			var c = str.charCodeAt(i);
			if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) 
			{
				len++;   
			}	
			else 
			{
				len+=2;   
			}
    	}
    }
    return len;
}  












function insertStr(soure, start, newStr){   

   return soure.slice(0, start) + newStr + soure.slice(start);
}

























export default {
  mixins: [
    modalMixin,
  ],

  props: {
    editType: {
      type: String,
      default: 'create',
    },
    editItem: Object,
  },
  data () {
    return {
      deviceType: [
        // { name: 'F800W', value: 'F800W' },
      ],
      IDcareType: [
        { name: this.$t("visitorsIndex.visitorsIDCard"), value:"居民身份证" },
        { name: this.$t("visitorsIndex.visitorsExit"), value: "港澳通行证" },
        { name: this.$t("visitorsIndex.visitorsPassport"), value: "护照" },
      ],
      ifAdvanced: false,
      formData: _.cloneDeep(DEFAULT_FORM),
      formRule: {
        phone: {required: true, validator: (rule, value, callback) => {
			let reg=/^1(3|4|5|6|7|8|9)\d{9}$/
			console.log('phone',!value,value)
			if(!value){
				return callback(new Error(this.$t("companyManagement.phoneTip")))
			}
            else if(value&&reg.test(value) == false) {
              return callback(new Error(this.$t("companyManagement.phoneTip")))
            }else{
              return callback()
            }
          } , trigger: 'blur'
        },
        // IDcareNum: { validator: (rule, value, callback) => {
		// 	const regIdCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        //     let errMsg
        //     if (
        //       value
        //       && value !== ''
        //       && !regIdCard.test(value)
        //     ) {
        //       errMsg = this.$t('visitorsIndex.visitorsCardNum1')
        //     }
        //     if (errMsg) {
        //       return callback(new Error(errMsg))
        //     }
        //     callback()
        //   } , trigger: 'blur'
        // },
        IDcareType: { required: true, message: this.$t("visitorsIndex.visitorsIDTypeSel") },
        startday: { required: true, message: this.$t("visitorsIndex.visitorsStartTimeSel") },
        endDay: { required: true, message: this.$t("visitorsIndex.visitorsEndTimeSel") },
        // IDcareNum: { required: true, message: this.$t("visitorsIndex.visitorsIDNumberI") },
	  },
	  recordTypes: [],
	  recordType: [],
	  areaName:"",
	  user:JSON.parse(window.localStorage.getItem('user'))||''
    }
  },
  computed: {
    ...mapState([
      'departId',
    ]),
    ifSelFile () {
      return typeof this.formData.file === 'object'
    },
  },

  mounted () {
	this.show = true
	this.getSiteList()
    if (this.editType === 'update') {
	  const formData = {}
	  console.log(this.editItem)
	  	if (!this.editItem.areaId) {
			  this.editItem.areaId = ''
		}
		this.formData = {
			IDcareType:this.editItem.cardType,
			deviceType:this.editItem.areaId,
			phone:this.editItem.phone,
			startday:this.editItem.startTime,
			endDay:this.editItem.endTime,
			photo:this.editItem.photo,
			file:'',
		}
		$("#personName").val(this.editItem.realName)
		$("#IDcareNum").val(this.editItem.cardNum)
		this.getParent()
    }else{
      console.log('我是新增')
      const myDate = new Date();
      const year = myDate.getFullYear(); // 获取当前年份
      const month = myDate.getMonth() + 1; // 获取当前月份(0-11,0代表1月所以要加1);
      const day = myDate.getDate(); // 获取当前日（1-31）
      // 日期格式：2019/07/29 - 2019/07/29
      this.formData.startday = `${year}-${month}-${day}  06:00:00`
      this.formData.endDay = `${year}-${month}-${day}  23:59:00`
    }
	
	
  },

  methods: {
    getPhoto,
    handleUpload (file) {
      console.log(file)
      this.formData.file = file
	  this.formData.photo = ''
	//   this.ifSelFile = true
      return false
    },
    onSelectIDcard (val) {
      console.log(val)
      if (val == '居民身份证') {
        this.ifAdvanced = true
      } else {
        this.ifAdvanced = false
      }
	},
	startdayChange (obj) {
		console.log(obj)

	},
	endDayChange (obj) {
		console.log(obj)
	},
    aaaa () {
      var device = new Device();
      var myDevice = device.createDevice("Cert");
      //显示提示信息
      myDevice.setMessage();
      setting.Methods.checkWebServer(myDevice);
	},
	generateFormData (obj) {
      const data = _.cloneDeep(obj)
      // data.depId = this.selectedDepart
      // if (_.isDate(data.birthday)) {
      //   data.birthday = moment(data.birthday).format('YYYY-MM-DD')
      // } else {
      //   data.birthday = ''
      // }
      // if (!data.worknum) {
      //   data.worknum = ''
      // }
      // if (_.isDate(data.jointime)) {
      //   data.jointime = moment(data.jointime).format('YYYY-MM-DD')
      // } else {
      //   data.jointime = ''
      // }
      const formData = new FormData()
      const keys = Object.keys(data)
      for (let i = 0; i < keys.length; i += 1) {
        const key = keys[i]
        formData.append(key, data[key])
      }
      return formData
    },
    async handleSubmit () {
      const ifVlid = await this.$refs.form.validate()
      if (ifVlid && this.editType === 'create') {
        this.handleCreate()
      }
      if (ifVlid && this.editType === 'update') {
        this.handleUpdate()
      }
    },

    async handleCreate () {
		console.log('handleCreate',this.formData.startday,this.formData.endDay,this.recordType,this.areaName)
		var formDataA = {
			cardType: this.formData.IDcareType ,
			areaId: this.formData.deviceType||this.recordTypes[0].value,
			areaName:this.areaName,
			realName:$("#personName").val(),
			phone: this.formData.phone,
			startTime: format(this.formData.startday, 'yyyy-MM-dd HH:mm:ss'),
			endTime: format(this.formData.endDay, 'yyyy-MM-dd HH:mm:ss'),
			cardNum:$("#IDcareNum").val(),
		}
		
		
		// return
		if(this.ifAdvanced){
			//身份证
			formDataA.photo  =  $("#id_img_pers").attr('src')
			formDataA.file = ''
		}else{
			formDataA.file = this.formData.file
			formDataA.photo = ''
		}
		if(!$("#IDcareNum").val()){
			this.$Message.error(this.$t("visitorsIndex.visitorsIDNumberI"))
			return
		}
		
		let reg=/^[A-Za-z0-9]+$/
		if (reg.test($("#IDcareNum").val()) == false) {
			this.$Message.error(this.$t("visitorsIndex.visitorsCardNum1"))
			return
		}
		if(!$("#personName").val()){
			this.$Message.error(this.$t("visitorsIndex.visitorsInputName"))
			return
		}
		var date = new Date(this.formData.startday);
		var date1 = new Date(this.formData.endDay);
		if (date.getTime() >= date1.getTime()) {
			this.$Message.error({
                content: this.$t("visitorsIndex.visitorsInputTime"),
                duration: 5
            })
			return
		}
		
      const formData = this.generateFormData(formDataA)
	  const { success , data} = await create(formData)
      if (success) {
			this.$Message.success(this.$t('devicesCreate.devCreateS'))
			this.ifUpdateUpper = true
			this.$_modal_close()
      } else {
		  console.log(data)
		if(data == '身份证号已存在'){
			this.$Message.error(this.$t('visitorsIndex.visitorsImgExist'))
		}else if(data == '图片格式错误'){
			this.$Message.error(this.$t('visitorsIndex.visitorsImgErrer'))
		}else{
        	this.$Message.error(this.$t('devicesCreate.devCreateN'))
		}

      }
    },
    async handleUpdate () {
      var formDataA = {
			cardType: this.formData.IDcareType ,
			areaId: this.formData.deviceType,
			realName:$("#personName").val(),
			phone: this.formData.phone,
			startTime: format(this.formData.startday, 'yyyy-MM-dd HH:mm:ss'),
			endTime: format(this.formData.endDay, 'yyyy-MM-dd HH:mm:ss'),
			cardNum:$("#IDcareNum").val(),
			id: this.editItem.id,
			mid: this.editItem.mid,
			areaName: this.editItem.areaName,
		}
		
		if(this.editType === 'update' && !this.ifSelFile && this.formData.photo&&!this.ifAdvanced){
			formDataA.photo = ''
			formDataA.file = ''
		}else{
			console.log(1234568)
			if(this.ifAdvanced){
				//身份证
				formDataA.photo  =  $("#id_img_pers").attr('src')
				formDataA.file = ''
			}else{
				formDataA.file = this.formData.file
				formDataA.photo = ''
			}
		}

		if(!$("#IDcareNum").val()){
			this.$Message.error(this.$t("visitorsIndex.visitorsIDNumberI"))
			return
		}
		let reg=/^[A-Za-z0-9]+$/
		if (reg.test($("#IDcareNum").val()) == false) {
			this.$Message.error(this.$t("visitorsIndex.visitorsCardNum1"))
			return
		}
		if(!$("#personName").val()){
			this.$Message.error(this.$t("visitorsIndex.visitorsInputName"))
			return
		}
		var date = new Date(this.formData.startday);
		var date1 = new Date(this.formData.endDay);
		if (date.getTime() >= date1.getTime()) {
			this.$Message.error({
                content: this.$t("visitorsIndex.visitorsInputTime"),
                duration: 5
            })
			return
		}
		
      const formData = this.generateFormData(formDataA)
      const { success, data } = await update(formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateUpdateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
		// this.$Message.error(this.$t('devicesCreate.devCreateUpdateN'))
		 console.log(data)
		if(data == '身份证号已存在'){
			this.$Message.error(this.$t('visitorsIndex.visitorsImgExist'))
		}else if(data == '图片格式错误'){
			this.$Message.error(this.$t('visitorsIndex.visitorsImgErrer'))
		}else{
        	this.$Message.error(this.$t('devicesCreate.devCreateN'))
		}
      }
	},
	async getDataArea (query) {
      var that = this
      const { success, data } = await getListArea({
        page: 1,
        limit: 500,
        usernames: '',
      })
      if (success) {
        if (data.data.length) {
        //   data.data.forEach((item, index) => {
        //     item.searchResults = that.areaNameS
		//   })
			that.deviceType = data.data
        }
      } else {
		  console.log(data)
		if(data == '身份证号已存在'){
			this.$Message.error(this.$t('visitorsIndex.visitorsImgExist'))
		}else if(data == '图片格式错误'){
			this.$Message.error(this.$t('visitorsIndex.visitorsImgErrer'))
		}else{
        	this.$Message.error(this.$t('devicesCreate.devCreateN'))
		}

      }
	},
	async getSiteList(){
      let data1={
        areaName:'',
        areaType:'',
      }
    	const { success ,data} = await getSite(data1)
      if (success) {  
		
        const list=data.data
        let listString = JSON.stringify(list).replace(/"id"/g, '"value"')
        let listStringLabel = listString.replace(/"areaName"/g, '"label"')
        let listStringChildren = listStringLabel.replace(/"children"/g, '"children"')
		var aParse = JSON.parse(listStringChildren)
		var firstItem=aParse[0].value
		var that=this
        function dG(params) {
        params.forEach(v=>{	
			if(v.value!=firstItem){
				if(that.user.type!='0'){
					if(v.areaType=='D'&&v.value!=that.user.areaId){
						v.disabled=true
					}
				}
			}
			
          if(v.children){
            dG(v.children)
          }else{
			v.children=[]
			// if(that.user.type!='0'){
			// 	if(v.areaType=='D'&&v.value!=that.user.areaId){
			// 		v.disabled=true
			// 	}
			// }
          }
        })
      }
	dG(aParse)
	if(aParse&&aParse[0].label==="新场所"){
          let arr11=aParse
          arr11[0].label=this.$t('title.newSite')
          this.recordTypes=arr11 
        }else{
          this.recordTypes=aParse 
		}
		this.areaName="新场所"
		console.log('this.recordTypes12',this.recordTypes)
		if(this.editType != 'update'){ 
          setTimeout(()=>{
            let arr=[]
            arr.push(this.recordTypes[0].value)
            this.recordType=arr     
		  },500)
		}
      } else {
        this.$Message.error(this.$t('staffIndex.stafferror'))
      }
    },
    // 获取上级场所
    async getParent(){
      let data1={
        id:this.editItem.areaId,
        parentId: this.editItem.parentId,
      }
      const { success ,data} = await getParentArea(data1)
      if (success) {
        setTimeout(() => {
          this.recordType=data.data
        }, 500);
        
      } else {
        this.$Message.error(this.$t('staffIndex.stafferror'))
      }
	},
	handleChange1 (value,item) {
      // Change时候赋值给recordType  然后关闭级联下拉框可以选中
	//   this.recordType = value
	console.log(value,item)
      if(value){       
		this.formData.deviceType = value[value.length-1]
		this.areaName=item[item.length-1].label
      }
    },
  },
}
</script>
<style lang="less" scoped>
.ivu-input-wrapper{
  width :70% !important;
}
.cssAll{
  border: 1px solid #dcdee2;
  width: 70%;
  height: 32px;
  text-indent: 8px;
  color: #515a6e;
  border-radius: 3px;
}
.cssAll::-webkit-input-placeholder { /* WebKit browsers */
   color: #c8cbd1;
}
.cssAll::-moz-placeholder { /* Mozilla Firefox 19+ */
   color: #c8cbd1;
}
.cssAll:-ms-input-placeholder { /* Internet Explorer 10+ */
   color: #c8cbd1;
}
.cssAll:hover {
    border-color: #57a3f3;
}
.cssAll:focus {
	outline: none;
	border-color: #57a3f3;
	box-shadow: 0 0 0 2px rgba(45,140,240,.2);
}
.img{
  width: 100px;
}
/deep/ .ivu-date-picker-cells-header span{
  white-space: nowrap;
  font-size: 13px;
}
</style>